package com.example.chenhaosblog.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * 上传文件的工具类
 *
 *
 *
 */
public class FileUpload {
	// 上传图片时的大小,不可超过50K
	final static long IMAGE_MAX_SIZE = 1024 * 50;
	// 上传excel文件，导入试卷大小不可以超过1M
	final static long XLS_MZX_SIZE = 1024 * 1024 * 5;

	public static String fileUpload(HttpServletRequest request, HttpServletResponse response, String path,
			String saveName) throws FileUploadException, IOException {
//		response.setContentType("text/html");
		// 实例化硬盘文件工厂,用来初始化上传组件fileUpload
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置上传文件时用于临时存放文件的内存大小,这里是4K,多余的部分将临时存在硬盘
		factory.setSizeThreshold(4096);
		factory.setRepository(new File(request.getRealPath("/") + "resource"));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(XLS_MZX_SIZE);
		List fileList = upload.parseRequest(request);
		Iterator iter = fileList.iterator();
		String fExt = "";
		while (iter.hasNext()) {
			FileItem item = null;
			String newPath = null;
			// 获得当前文件
			item = (FileItem) iter.next();
			// 忽略表单中不是文本域的字段
			if (item == null || item.isFormField()) {
				continue;
			}
			// 得到文件的完整路径
			newPath = item.getName();
			// 得到去除路径的文件名
			String fName = newPath.substring(newPath.lastIndexOf("\\") + 1);
			// 得到文件的扩展名
			fExt = fName.substring(fName.lastIndexOf(".") + 1);
			// 设置存放文件的路径
			File saveFile = new File(path);
			if (!saveFile.exists()) {
				saveFile.mkdirs();
			}
			String saveFilePath = path + saveName + "." + fExt;
			try {
				item.write(new File(saveFilePath));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return saveName + "." + fExt;
	}
	public static String fileUploadNew(MultipartFile file,String savepath){
         String newFileName="";
        try {
         File dir = new File(savepath);
		if (!dir.isDirectory())
			dir.mkdir();

		String fileOriginalName = file.getOriginalFilename();
		 newFileName = UuidUtil.get32UUID() + fileOriginalName.substring(fileOriginalName.lastIndexOf("."));
		File writeFile = new File(savepath + newFileName);
		//文件写入磁盘

            file.transferTo(writeFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newFileName;//返回文件名称
	}
}
